const express = require('express');
const router = express.Router();
const Changelog = require('../models/Changelog');

// 获取变更日志列表
router.get('/', async (req, res) => {
  try {
    const { 
      personnelId, 
      sourceId, 
      changeType, 
      startDate, 
      endDate, 
      page = 1, 
      limit = 20 
    } = req.query;
    
    // 构建查询条件
    const query = {};
    if (personnelId) query.personnelId = personnelId;
    if (sourceId) query.sourceId = sourceId;
    if (changeType) query.changeType = changeType;
    
    // 日期范围
    if (startDate || endDate) {
      query.timestamp = {};
      if (startDate) query.timestamp.$gte = new Date(startDate);
      if (endDate) query.timestamp.$lte = new Date(endDate);
    }
    
    // 分页
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    // 查询总数
    const total = await Changelog.countDocuments(query);
    
    // 查询数据
    const changelogs = await Changelog.find(query)
      .sort({ timestamp: -1 })
      .skip(skip)
      .limit(parseInt(limit))
      .populate({
        path: 'personnelId',
        select: 'name position organization imageUrl detailUrl'
      })
      .populate({
        path: 'sourceId',
        select: 'name organization'
      });
    
    res.json({
      changelogs,
      pagination: {
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (error) {
    console.error('获取变更日志列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取单个变更日志详情
router.get('/:id', async (req, res) => {
  try {
    const changelog = await Changelog.findById(req.params.id)
      .populate({
        path: 'personnelId',
        select: 'name position organization imageUrl detailUrl'
      })
      .populate({
        path: 'sourceId',
        select: 'name organization listUrl'
      });
    
    if (!changelog) {
      return res.status(404).json({ message: '变更日志不存在' });
    }
    
    res.json(changelog);
  } catch (error) {
    console.error('获取变更日志详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取统计数据
router.get('/stats/summary', async (req, res) => {
  try {
    const { days = 30 } = req.query;
    
    // 计算日期范围
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));
    
    // 按类型统计变更数量
    const changesByType = await Changelog.aggregate([
      { $match: { timestamp: { $gte: startDate } } },
      { $group: { _id: '$changeType', count: { $sum: 1 } } }
    ]);
    
    // 按组织统计变更数量
    const changesByOrganization = await Changelog.aggregate([
      { $match: { timestamp: { $gte: startDate } } },
      { 
        $lookup: {
          from: 'sources',
          localField: 'sourceId',
          foreignField: '_id',
          as: 'source'
        }
      },
      { $unwind: '$source' },
      { $group: { _id: '$source.organization', count: { $sum: 1 } } },
      { $sort: { count: -1 } },
      { $limit: 10 }
    ]);
    
    // 按日期统计变更数量
    const changesByDate = await Changelog.aggregate([
      { $match: { timestamp: { $gte: startDate } } },
      {
        $group: {
          _id: { 
            $dateToString: { format: '%Y-%m-%d', date: '$timestamp' } 
          },
          count: { $sum: 1 }
        }
      },
      { $sort: { _id: 1 } }
    ]);
    
    res.json({
      changesByType,
      changesByOrganization,
      changesByDate
    });
  } catch (error) {
    console.error('获取变更统计数据失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取特定人员的变更历史
router.get('/personnel/:personnelId', async (req, res) => {
  try {
    const changelogs = await Changelog.find({ personnelId: req.params.personnelId })
      .sort({ timestamp: -1 })
      .populate({
        path: 'sourceId',
        select: 'name organization'
      });
    
    res.json(changelogs);
  } catch (error) {
    console.error('获取人员变更历史失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router; 